<?php

namespace App\Admin\Forms;

use App\Models\Order;
use App\Services\Facades\OrderService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class OrderStatusForm extends Form implements LazyRenderable
{
    use LazyWidget;

    // 使用异步加载功能

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $status = $input['status'];
        $failReason = $input['fail_reason'];
        if (!in_array($status, [3, 4])) {
            return $this->response()->error('状态不正确');
        }
        $order = Order::findOrFail($this->payload['id']);
        if ($order->status != 2) {
            return $this->response()->error('状态不正确');
        }
        if ($status == 4 && $failReason == '') {
            return $this->response()->error('请填写驳回原因');
        }
        $order->status = $status;
        $order->fail_reason = $failReason ?? null;
        $order->save();


        //驳回的话 退回发布者金额和手续费
        //OrderService::rufund($order->order_number, bcadd($order->amount, $order->handling_fee), 2);
        return $this
            ->response()
            ->success('操作成功')
            ->refresh();
    }

    public function form()
    {
        // 获取外部传递参数
        //$id = $this->payload['id'] ?? null;

        $this->radio('status')->options([3 => '审核通过', 4 => '审核失败'])->when(4, function () {
            $this->text('fail_reason');
        })->required();
    }
}
